package com.srwl.mytx.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PictureAdapter;
import com.srwl.mytx.domain.Accusation;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.Comment;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.Task;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CommentService;
import com.srwl.mytx.service.TaskService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.SystemUtil;
import com.srwl.mytx.utils.Utils;
import com.google.android.material.bottomsheet.BottomSheetBehaviorV2;
import com.srwl.mytx.widget.CountDownView;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.CommentBottomBar;
import com.srwl.mytx.widget.CommentDialog;
import com.srwl.mytx.widget.CommentView;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.MultipleCouponView;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.OfferDialogV1;
import com.srwl.mytx.widget.PeriscopeLayout;
import com.srwl.mytx.widget.TitleBar;
import com.srwl.mytx.widget.TopicDonationView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import qiu.niorgai.StatusBarCompat;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TopicDetailsActivity extends BaseActivity implements View.OnClickListener, CommentView.InteractionListener, CommentBottomBar.InteractionListener, TopicDonationView.InteractionListener, TitleBar.InteractionListener, BottomDialog.InteractionListener, CommentDialog.InteractionListener, MultipleCouponView.InteractionListener {
    private static final String TAG = "TopicDetailsActivity";
    private static final int REQUEST_CODE_TO_TASK_DETAIL_ACTIVITY = 0;
    private static final int REQUEST_CODE_EDIT_TOPIC = 1;
    public static final int REQUEST_CODE_FORWARD_DONATION = 3;//转发捐赠
    private int lastState;

    public static void startActivity(Activity activity, Topic topic) {
        if (activity == null) {
            Log.e(TAG, "startActivity: context 不能为空");
            return;
        }
        if (topic == null) {
            Log.e(TAG, "startActivity: topicId 不能为空");
            return;
        }
        activity.startActivity(new Intent(activity, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
    }

    public static void startActivity(Context context, String topicId) {
        if (context == null) {
            Log.e(TAG, "startActivity: context 不能为空");
            return;
        }
        if (topicId == null) {
            Log.e(TAG, "startActivity: topicId 不能为空");
            return;
        }
        context.startActivity(new Intent(context, TopicDetailsActivity.class).putExtra("topicId", topicId));
    }

    public static void startActivity(Activity activity, Topic topic, int requestCode) {
        if (activity == null) {
            Log.e(TAG, "startActivity: context 不能为空");
            return;
        }
        if (topic == null) {
            Log.e(TAG, "startActivity: topicId 不能为空");
            return;
        }

        activity.startActivityForResult(new Intent(activity, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), requestCode);
    }

    public static void startActivity(Activity activity, String topicId, int requestCode) {
        if (activity == null) {
            Log.e(TAG, "startActivity: activity 不能为空");
            return;
        }
        if (topicId == null) {
            Log.e(TAG, "startActivity: topicId 不能为空");
            return;
        }
        activity.startActivityForResult(new Intent(activity, TopicDetailsActivity.class).putExtra("topicId", topicId), requestCode);
    }

    private Topic topic;
    private String topicId;
    private User author;
    private PictureAdapter pictureAdapter;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refreshLayout.setFooterView(new NodataFooter(TopicDetailsActivity.this));
        }
    };

    //    @BindView(R.id.iv_chat)
//    ImageView iv_chat;
    @BindView(R.id.top_bar)
    TitleBar topBar;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.rv_picture_list)
    RecyclerView rv_pictureList;
    //    @BindView(R.id.rv_comment_list)
//    CommentListView commentListView;
    @BindView(R.id.sv_container)
    NestedScrollView sv_container;
    @BindView(R.id.periscope_layout)
    PeriscopeLayout periscopeLayout;
    @BindView(R.id.video_player)
    JzvdStd videoPlayer;
    @BindView(R.id.ll_reward)
    LinearLayout ll_reward;
    @BindView(R.id.tv_reward)
    TextView tv_reward;
    //    @BindView(R.id.tv_deposit)
//    TextView tv_deposit;
//    @BindView(R.id.tv_donation_amount_1)
//    TextView tv_donationAmount1;
    @BindView(R.id.tv_donation_amount)
    TextView tv_donationAmount;
    @BindView(R.id.tv_donation_count)
    TextView tv_donationCount;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.comment_bottom_bar)
    CommentBottomBar commentBottomBar;
    @BindView(R.id.donation_view)
    TopicDonationView donationView;
    @BindView(R.id.ll_location)
    LinearLayout ll_location;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.comment_view)
    CommentView commentView;
    @BindView(R.id.iv_red_packet)
    MultipleCouponView couponView;
    @BindView(R.id.count_down_view)
    CountDownView countDownView;
    @BindView(R.id.tv_auction_price)
    TextView tv_auctionPrice;
    @BindView(R.id.auction_view)
    LinearLayout auctionView;
    @BindView(R.id.tv_receive_task_size)
    TextView tv_receiveTaskSize;
    @BindView(R.id.btn_receive_task)
    Button btn_receiveTask;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.root_layout)
    RelativeLayout rootLayout;

    private boolean bottomBarIsHide;
    private boolean isShowingHideAnimate;
    private boolean isShowingDisplayAnimate;
    private ViewAnimator viewAnimator;//bottomBar滑动动画

    private List<String> pictures = new ArrayList<>();
    private boolean hasVideo = true;
    private BottomSheetBehaviorV2<View> bottomSheetBehavior;
    private boolean isManager;
    private Integer receiveTaskSize;
    private boolean isGetTheTask;
    private boolean topicChange;
    //下架 就是悬赏撤回
    private boolean topicBackOut;
    private boolean topicDelete;
    private Task task;
    private boolean hadAccusation;  //表示是否对该主题举报过，暂时就先创建该对象的时候就默认为false，减少多次重复举报的风险

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            finish();
        }
        setContentView(R.layout.activity_topic_details);
        ButterKnife.bind(this);
        initBottomSheetBehavior();
        topic = getIntent().getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        topicId = getIntent().getStringExtra("topicId");
        if (topic != null) {
            topicId = topic.getId();

            //如果传入了 topic ,就先执行初始化，并下载数据，下载数据结束后，刷新部分View
            init();
            loadTopicData(topicId, false);
        } else {
            //传入的是主题id,下载数据后，下载数据结束后，初始化全部View
            loadTopicData(topicId, true);
        }
        initRefreshLayout();

        //如果是点击评论图标跳转到本页面，则让评论视图显示出来
        String commentExtra = getIntent().getStringExtra(Constant.EXTRA_INFO_MESSAGE);
        if ("comment".equals(commentExtra)) {
            commentBottomBar.et_content.setHint("说点什么");
            onPrepareComment();
            commentBottomBar.displayCommentEditView();
        }
    }

    private void initBottomSheetBehavior() {
        bottomSheetBehavior = BottomSheetBehaviorV2.fromV2(findViewById(R.id.comment_view));
        bottomSheetBehavior.setHideable(true);
        //设置默认先隐藏
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View view, int newState) {
                Log.d(TAG, "onStateChanged: " + newState);

                if ((newState == BottomSheetBehavior.STATE_SETTLING || newState == BottomSheetBehavior.STATE_COLLAPSED) && lastState == BottomSheetBehavior.STATE_EXPANDED) {//如果从完全展示到开始收折，那么隐藏软键盘
                    hideSoftKeyboard();
                    commentBottomBar.showHint("说点什么");
                    commentView.prepareComment();
                }
                if (newState == BottomSheetBehavior.STATE_EXPANDED || newState == BottomSheetBehavior.STATE_COLLAPSED || newState == BottomSheetBehavior.STATE_HIDDEN) {
                    lastState = newState;
                }
//                if (newState == BottomSheetBehavior.STATE_SETTLING) {//&& slideOffset < 0
//                    if ((lastStatus == BottomSheetBehavior.STATE_COLLAPSED && slideOffset <= 0) || (lastStatus == BottomSheetBehavior.STATE_EXPANDED && bottomSheetBehavior.getSkipCollapsed())) {
//                    }
//                }
//                if (newState == BottomSheetBehavior.STATE_COLLAPSED || (newState == BottomSheetBehavior.STATE_EXPANDED)) {
//                    lastStatus = newState;
//                }
//                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
//                    commentBottomBar.hideCommentEditView();
//
//                }


            }

            @Override
            public void onSlide(@NonNull View view, float slideOffset) {
                float scrollY = ((1 + slideOffset) * view.getHeight());
                if (!Float.isNaN(scrollY)) {
                    Log.d(TAG, "scrollY: " + scrollY);
                    commentBottomBar.setCommentLayoutTranslationY(scrollY);
                }

            }
        });
    }


    private void init() {
        Log.d(TAG, topic.toString());
        User manager = topic.getManager();
        if (manager != null) {
            isManager = TextUtils.equals(manager.getuId(), UserProfileManager.getInstance().getLoginUserInfo().getuId());
        }
        author = topic.getManager();
        pictures.clear();
        pictures.addAll(topic.getPictures());
        topBar.init(topic.getTitle(), this);
        hasVideo = !TextUtils.isEmpty(topic.getVideo());

        if (hasVideo) {//改变一些ui,适配VideoPlayer
            //判断是否是刘海屏（对华为 小米 oppo vivo 4个手机品牌做判断）
            NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
                @Override
                public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                    Log.i(TAG, "Is this screen notch? " + notchScreenInfo.hasNotch);
                    if (!notchScreenInfo.hasNotch) {
                        //如果不是刘海屏，就设置为全屏
                        SoftKeyboardFixerForFullscreen.assistActivity(TopicDetailsActivity.this); //设置全屏必须要这样设置，否则 软件不会把输入框 顶上来，adjustResize 会失效
                        StatusBarCompat.translucentStatusBar(TopicDetailsActivity.this, true);
                        topBar.adaptVideo();
                        //设置评论View 的顶部占位栏的高度（为了不遮住状态栏）
                        int statusBarHeight = Utils.getStatusBarHeight(TopicDetailsActivity.this);
                        if (statusBarHeight == 0) {
                            statusBarHeight = Utils.dpToPx(20, TopicDetailsActivity.this); //如果没获取到 状态栏高度，按20dp 处理
                        }
                        commentView.setPlaceHolderHeight(statusBarHeight);
                    } else {
                        topBar.adaptVideoHasNotch();
                        commentView.setPlaceHolderHeight(0);
                    }
                }
            });

            //bottomBar 在布局文件中设置的高度是45dp ，因为在onCreate（）里面没法获取View的高度
            commentBottomBar.scrollBackground(-Utils.dpToPx(R.dimen.topic_bottom_bar_height, this));
            ViewGroup.LayoutParams params = videoPlayer.getLayoutParams();
            if (TextUtils.equals("MI 8 SE", SystemUtil.getSystemModel())) {//小米8se ，不能满屏，必须手动设置高度，获取的屏幕高度是2029，也是不准确的，
                params.height = 2164;
            } else {
                params.height = screenHeight;//设置videoPlayer 高度为屏幕可见高度 比如显示底部导航栏的手机，导航栏128像素的高度，那么这儿获取的 heightPixels 为1792
            }
            //视频封面加载不使用缩略图方式，因为在主题列表中，视频封面也是加载的全质量的图，而没有使用压缩策略，在这儿，也是需要加载全质量的图，
            //如果以后视频封面的图片质量提高，在列表中使用了压缩策略，那在这儿应该使用缩略图方式，让已经加载到本地的小图 先显示出来
            String coverUrl = Utils.getCoverUrl(topic, "");
            //Glide.with(this).load(coverUrl).into(videoPlayer.thumbImageView);
            GlideLoadUtils.glideLoad(this, coverUrl, videoPlayer.thumbImageView);
            LinkedHashMap map = new LinkedHashMap();
            String url = topic.getVideo();
            String remoteUrl;
            if (url != null && url.startsWith("http")) {
                remoteUrl = url;
            } else {
                remoteUrl = AliOssService.TOPIC_VIDEO_PRE_URL + url;
            }
            String proxyUrl = MyApplication.getProxy(this).getProxyUrl(remoteUrl);//视频缓存代理
            map.put("高清", proxyUrl);
            JZDataSource jzDataSource = new JZDataSource(map, "");
            jzDataSource.looping = false;
            // jzDataSource.currentUrlIndex = 2;
            videoPlayer.setUp(jzDataSource, JzvdStd.SCREEN_FULLSCREEN);
            videoPlayer.hideAllViewAdaptFullScreen();
            videoPlayer.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            JzvdStd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_CROP);
            videoPlayer.setVisibility(View.VISIBLE);
            videoPlayer.startVideo();
            RelativeLayout.LayoutParams paramsTop = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            refreshLayout.setLayoutParams(paramsTop);
            //  videoPlayer.setUp(topic.getVideo(), "", JzvdStd.SCREEN_WINDOW_NORMAL);
        } else {
            //如果没有视频的情况下，让sv_container 位于top_bar的下方，不然top_bar会遮住一部分内容
            JzvdStd.resetAllVideos();
            commentView.setPlaceHolderHeight(0);
            videoPlayer.setVisibility(View.GONE);
            topBar.updateTopBar();
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.BELOW, R.id.top_bar);
            refreshLayout.setLayoutParams(params);


        }
        initPicturesList();
        setOnScrollListener();
//        commentBottomBar.init(topic, (topic.getCommentSize() == null) ? 0 : topic.getCommentSize(), topic.getPraiseSize() == null ? 0 : topic.getPraiseSize(), this);

        tv_content.setText(topic.getContent());
        tv_address.setText(topic.getAddress());

        // tv_goodsPrice.setText(String.format("RMB：%s", Utils.numberFormat(topic.getPrice())));

        //拍卖，暂时注销
        // tv_goodsPrice.setText("RMB" + topic.getAuctionPrice());

        // iv_chat.setOnClickListener(this);

        ll_location.setOnClickListener(this);
        // initMultipleCouponView();
        Integer topicType = topic.getType();
        if (topicType != null && topicType == Constant.TOPIC_TYPE_REWARD) {
            ll_reward.setVisibility(View.VISIBLE);
            tv_reward.setText(Utils.numberFormat(topic.getPrice()));
            receiveTaskSize = topic.getReceiveTaskSize();
            if (receiveTaskSize == null) {
                receiveTaskSize = 0;
            }
            tv_receiveTaskSize.setText(receiveTaskSize + "");
//            isGetTheTask = topic.isHadReceive();
//            showTaskStatus();
//            donationView.setVisibility(View.VISIBLE);
//            donationView.init(topic, this);
            btn_receiveTask.setOnClickListener(v -> {
                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                    startActivity(new Intent(TopicDetailsActivity.this, LoginActivity.class).putExtra("EXTRA_CONTENT", "领取悬赏任务需要先登录"));
                    return;
                }
                if (isGetTheTask) {
                    //如果已经获取了任务，点击跳转到任务详情
                    toTaskDetail();
                } else if (isManager) {
                    if (receiveTaskSize == 0) {
                        showToast("暂时还没有任务领取记录");
                    } else {
                        //悬赏发布者进入任务领取记录页面
                        toTaskReceiveRecord();
                    }
                } else {
                    Integer status = topic.getStatus();
                    if (status != null) {

                        if (status == Constant.TOPIC_STATUS_REWARD_EXECUTING) {

                            ConfirmDialog dialog = new ConfirmDialog(TopicDetailsActivity.this, "提示", "悬赏已经在执行中，不能继续操作");
                            dialog.show();
                        } else if (status == Constant.TOPIC_STATUS_REWARD_COMPLETE) {
                            ConfirmDialog dialog = new ConfirmDialog(TopicDetailsActivity.this, "提示", "悬赏已经完结，不能继续操作");
                            dialog.show();
                        } else if (status == Constant.TOPIC_STATUS_REWARD_CANCEL) {
                            ConfirmDialog dialog = new ConfirmDialog(TopicDetailsActivity.this, "提示", "悬赏已经取消，不能继续操作");
                            dialog.show();
                        } else {
                            generateTask();
                        }
                    } else {
                        Log.e(TAG, "init: 主题状态是空的，，，，");
                    }
                }
            });
        }
//        else if (topicType != null && (topicType == Constant.TOPIC_TYPE_AREA || topicType == Constant.TOPIC_TYPE_SCHOOL || topicType == Constant.TOPIC_TYPE_INDUSTRY)) {
//            donationView.setVisibility(View.VISIBLE);
//            donationView.init(topic, this);
//        }
        //显示捐赠总额
        if (topic.getDonationReceived() != null) {
            tv_donationAmount.setText(topic.getDonationReceived() + "");
        } else {
            tv_donationAmount.setText("0.00");
        }

        //如果是拍卖类型，就展示拍卖倒计时和底价，而当前价最高价就没有显示，因为当前价没有同步到ES，从ES 搜索出来的topic中的当前价是不正确的，它仅仅是最初生成的时候保存进去的值
        if (topic.getType() == Constant.TOPIC_TYPE_AUCTION) {
            countDownView.init(topic.getStartTime(), topic.getStopTime(), null);
            tv_auctionPrice.setText(Utils.moneyFormat(topic.getAuctionPrice()));
            auctionView.setVisibility(View.VISIBLE);
            auctionView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OfferDialogV1 offerDialog = new OfferDialogV1(TopicDetailsActivity.this, topic, new OfferDialogV1.InteractionListener() {
                        @Override
                        public void onOfferSuccess(double amount) {

                        }
                    });
                    offerDialog.show();
                }
            });
        }

//        donationView.init(topic);
        commentView.init(topic, this);
    }

    /**
     * 获取任务，并跳转
     */
    private void toTaskDetail() {
        if (task != null) {
            task.setTargetTopic(topic);
            TaskDetailActivity.startActivity(this, task, REQUEST_CODE_TO_TASK_DETAIL_ACTIVITY);
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .getMyTaskInfoByTopicId(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取任务信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        task = body.toJavaObject(Task.class);
                        task.setTargetTopic(topic);
                        startActivity(new Intent(TopicDetailsActivity.this, TaskDetailActivity.class).putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                    }
                });
    }

    private void toTaskReceiveRecord() {
        TaskReceivedRecordActivity.startActivity(this, topicId);
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(true);
//        if (donationView.getVisibility() != View.VISIBLE) {
//            refreshLayout.setDisableLoadMore(true);
//            return;
//        }
        refreshLayout.setEnableOverScroll(true);//不能是 false 否则滑动后，第一次点击事件 会被消耗
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                //  refreshData();
            }

            @Override
            public void onLoadingMore() {
                if (donationView.isHasNextPage()) {
                    donationView.loadData();
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }

    /**
     * 下载 悬赏 领取情况和 捐赠数据,评论数量
     */
    private void loadTopicData(String topicId, boolean refreshAllView) {

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .getTopicFromMysql(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.PARAMETER_INVALID:
                                    break;
                                case Constant.DOC_ID_INVALID:
                                    showToast_v1("当前主题已被删除！");
                            }
                            // showToast(getString(R.string.system_busy));
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        if (data == null) {
                            return;
                        }
                        Log.d(TAG, "onResponse: 从后端查询回来的topic 数据：" + data.toString());
                        topic = data.toJavaObject(Topic.class);
                        //topicChange = true;
                        //当前客户端访问服务器端拉取最新的数据的时候,判断是否需要改变按钮的状态
                        Integer topicType = topic.getType();
                        if (topicType != null && topicType == Constant.TOPIC_TYPE_REWARD) {
                            isGetTheTask = topic.isHadReceive();
                            showTaskStatus();
                        }
                        //目前任何类型的主题，都可以接受捐赠
                        donationView.setVisibility(View.VISIBLE);
                        donationView.init(topic, TopicDetailsActivity.this);
                        if (refreshAllView) {
                            init();
                        }
                        donationView.init(topic);
                        commentBottomBar.init(topic, (topic.getCommentSize() == null) ? 0 : topic.getCommentSize(), topic.getPraiseSize() == null ? 0 : topic.getPraiseSize(), TopicDetailsActivity.this);
                        initMultipleCouponView();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    private void showTaskStatus() {

        if (isGetTheTask) {
            taskReceived();
        } else if (topic.getStatus() == Constant.TOPIC_STATUS_REWARD_EXECUTING) {
            btn_receiveTask.setText("悬赏执行中");
        } else if (topic.getStatus() == Constant.TOPIC_STATUS_REWARD_COMPLETE) {
            rewardComplete();
        } else if (topic.getStatus() == Constant.TOPIC_STATUS_REWARD_CANCEL || topic.getStatus() == Constant.TOPIC_STATUS_DELETE) {//当悬赏取消（悬赏拆回后）或者是 删除后，都显示 悬赏取消
            rewardCancel();
        } else if (isManager) {
            btn_receiveTask.setText("查看领取记录");
        } else {
            btn_receiveTask.setText("领取任务");
        }
    }

    private void initMultipleCouponView() {
        Integer topicType = topic.getType();
        //学习、地区、行业类型的主题，任何人可以在里面发红包
        if (topicType != null && (topicType == Constant.TOPIC_TYPE_AREA || topicType == Constant.TOPIC_TYPE_SCHOOL || topicType == Constant.TOPIC_TYPE_INDUSTRY)) {
            couponView.init(topic);
        } else {  //其他类型的主题，只有作者自己或者是有红包存在的情况下，初始化红包，等于说只有自己可以给自己的主题发红包

            if (isManager || topic.getCoupon() != null) {
                couponView.init(topic);
            }
        }
        couponView.setListener(this);

    }

    @Override
    protected void onNewIntent(Intent intent) {     //解决singleTask模式下跳转的activity由于复用实例而造成的数据未更新的问题
        super.onNewIntent(intent);
        topic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        if (topic != null) {
            topicId = topic.getId();
            init();
            loadTopicData(topicId, false);
        } else {
            topicId = getIntent().getStringExtra("topicId");
            loadTopicData(topicId, true);
        }
        //隐藏CommentView，因为有些时候是在打开commentView的情况下复用该activity，导致即使是跳转到已经更新数据的activity中，commentView还是打开状态
        hideCommentView();
        commentBottomBar.hideCommentEditView();

    }


    private void initPicturesList() {
        //主题有可能是每页图片的
        if (topic.getPictures() == null || topic.getPictures().size() == 0) {
            return;
        }
        if (pictureAdapter == null) {
            pictureAdapter = new PictureAdapter(this, pictures);
            LinearLayoutManager linearLayoutManager_1 = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
            rv_pictureList.setLayoutManager(linearLayoutManager_1);
            rv_pictureList.setAdapter(pictureAdapter);
            //不加这句，滑动不顺畅，加了这句，recyclerView的item 一次全部加载了，
            rv_pictureList.setNestedScrollingEnabled(false);
            if (rv_pictureList.getRecycledViewPool() != null) {
                rv_pictureList.getRecycledViewPool().setMaxRecycledViews(0, 10);
            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    pictureAdapter.notifyDataSetChanged();//不加这句，通过onNewIntent调用init（）的时候，图片并不会更新
                }
            });

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.iv_chat:
//                User u = new User(author.getuId());
//                u.setUsername(author.getUsername());
//                u.setAvatar(author.getAvatar());
//                u.setArea(author.getArea());
//                u.setGender(getGender(author));
//                // Boolean bol_isMyFriend = DemoHelper.getInstance().saveContanctInMemory(u);
//                startActivity(new Intent(TopicDetailsActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, author.getuId()));
//                break;
//            case R.id.iv_icon:
////                Bundle bundle1 = new Bundle();
////                bundle1.putSerializable("toUser", author);
////                startActivity(new Intent(TopicDetailsActivity.this, UserProfileActivity.class).putExtras(bundle1));
//                User u1 = new User(author.getuId());
//                u1.setUsername(author.getUsername());
//                u1.setAvatar(author.getAvatar());
//                u1.setArea(author.getArea());
//                u1.setGender(getGender(author));
//                //Boolean bol_isMyFriend1 = DemoHelper.getInstance().saveContanctInMemory(u1);
//                startActivity(new Intent(TopicDetailsActivity.this, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, author));
//
//                break;
            case R.id.ll_location:

                startActivity(new Intent(TopicDetailsActivity.this, LocationMapActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));

                break;

        }
    }

    private void setOnScrollListener() {
        sv_container.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideCommentView();
                return false;
            }
        });
        //view.OnScrollChangeListener 用这个接口的话，level必须大于 23
        sv_container.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // Log.d(TAG, "垂直方向滑动距离：" + scrollY);
                if (videoPlayer.isShown()) {
                    topBar.scrollTitleBarBackground(scrollY, screenHeight);
                    scrollBottomBarBackground(scrollY);
                    if (videoPlayer.bottomProgressBar.isShown()) {
                        videoPlayer.bottomProgressBar.setVisibility(View.INVISIBLE);
                    }
                }


                if (scrollY < oldScrollY) {
                    // 向下滑动
                    // 下滑复位bottomBar: 视图rl_primary是GONE状态，那么让rl_primary显示出来
                    commentBottomBar.hideCommentEditView();
                    //   Log.d(TAG, "下滑，显示bottomBar");

                    // animateAndDisplayBottomBar(300);
                }


                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    //滑动到底部，隐藏bottomBar
                    //animateAndHideBottomBar();
                    Log.d(TAG, "滑动到底部了，获取更多评论:scrollY" + scrollY);

                }
            }
        });
    }

    private boolean hideCommentView() {
//        boolean keyBoardShowing = Utils.isKeyBoardShowing(this);
//        if (keyBoardShowing) {
//        }
        hideSoftKeyboard();
        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED || bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED || bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HALF_EXPANDED) {

            int screenHeight = getWindow().getDecorView().getHeight();
            Log.i(TAG, "hideCommentView: 屏幕高度:" + screenHeight);
            bottomSheetBehavior.setStateHidden(screenHeight);
//            if (keyBoardShowing) {
//            } else {
//                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
//            }
//            commentBottomBar.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    commentBottomBar.hideCommentEditView();
//                }
//            }, 500);
            return true;
        }
        return false;
    }


    void scrollBottomBarBackground(int scrollY) {
        if (scrollY - commentBottomBar.getHeight() <= 0) {

            commentBottomBar.scrollBackground(scrollY - commentBottomBar.getHeight());
        } else {
            commentBottomBar.scrollBackground(0);

        }
    }


    private void animateAndDisplayBottomBar(long duration) {
        if (!bottomBarIsHide || isShowingDisplayAnimate) {
            return;
        }
        if (viewAnimator == null) {
            viewAnimator = new ViewAnimator();
        }
        if (isShowingHideAnimate) {
            Log.d(TAG, "取消隐藏BottomBar的动画");
            viewAnimator.cancel();
        }
        isShowingDisplayAnimate = true;
        viewAnimator.animate(commentBottomBar).translationY(commentBottomBar.getTranslationY(), 0).duration(duration).onStop(new AnimationListener.Stop() {
            @Override
            public void onStop() {
                isShowingDisplayAnimate = false;
                bottomBarIsHide = false;
            }
        }).start();
    }

    private void animateAndHideBottomBar() {
        if (bottomBarIsHide || isShowingHideAnimate) {
            return;
        }
        if (isShowingDisplayAnimate) {
            Log.d(TAG, "取消显示BottomBar的动画");
            viewAnimator.cancel();
        }
        isShowingHideAnimate = true;
        if (viewAnimator == null) {
            viewAnimator = new ViewAnimator();
        }
        viewAnimator.animate(commentBottomBar).translationY(commentBottomBar.getTranslationY(), commentBottomBar.getHeight()).duration(300).onStop(new AnimationListener.Stop() {
            @Override
            public void onStop() {
                isShowingHideAnimate = false;
                // view.setVisibility(View.GONE);
                bottomBarIsHide = true;
            }
        }).start();


    }


    /**
     * 发表一个评论后，滑动scrollView，显示出自己发表的评论
     */
    void scrollToCommentView() {
//        ViewGroup firstCommentView = (ViewGroup) commentListView.getChildAt(0);
//        if (firstCommentView == null) {
//            return;
//        }
//        int showMoreCommentLayoutHeight = 0;
//        if (firstCommentView.findViewById(R.id.rl_show_more_child_comment) != null) {
//            showMoreCommentLayoutHeight = firstCommentView.findViewById(R.id.rl_show_more_child_comment).getHeight();
//        }
//        Log.d(TAG, "onResponse:showMoreCommentLayoutHeight     " + showMoreCommentLayoutHeight);
//        if (isCover(firstCommentView)) {
//            int scrollY = commentListView.getTop() - sv_container.getHeight() + firstCommentView.getHeight() - showMoreCommentLayoutHeight;
//
//            Log.d(TAG, "scrollToCommentView: sv_container.getHeight()" + sv_container.getHeight());
//            Log.d(TAG, "onResponse: 需要滑动到评论区" + scrollY);
//
//            if (!bottomBarIsHide || isShowingDisplayAnimate) {//如果bottomBar 是显示状态，显示一个评论 +bottomBar 的高度
//                scrollY += commentBottomBar.getHeight();
//            }
//            sv_container.scrollTo(0, scrollY);
//
//        }
    }


    void showBottomDialog() {

        List<String> items = new ArrayList<>();
        if (isManager) {//如果此topic的发布者就是自己
            items = Utils.generateTopicBottomDialogItems(topic);

        } else {
            items.add(Constant.BOTTOM_ITEM_NAME_ACCUSATION);
        }

        BottomDialog bottomDialog = new BottomDialog(this, items, this);
        bottomDialog.show();

    }

    /**
     * 举报主题
     */
    void accusationTopic(Accusation accusation) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .accusationTopic(accusation)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        Log.d(TAG, "onResponse: 举报完成");
                        showToast(getString(R.string.accusation_complete));
                        hadAccusation = true;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        progressBar.setVisibility(View.GONE);

                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    void revokeReward() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .revokeReward(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.REWARD_TOPIC_ALREADY_CANCEL:
                                    showToast("主题已经撤回,不可重复撤回4");
                                    break;
                                case Constant.REWARD_TOPIC_STATUS_ERROR:
                                    showToast("还有任务没有处理,不能撤回");
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        double deposit = ((BigDecimal) result.getData()).doubleValue();
                        //刷新保证金
                        UserProfileManager.getInstance().setDeposit(deposit);
                        topic.setStatus(Constant.TOPIC_STATUS_REWARD_CANCEL);
                        //主题改变 和主题下架，这两个状态是针对不同的页面而设置的，因为同一个操作，对不同的回跳页面，需要做不同的处理。
                        topicChange = true;
                        topicBackOut = true;
                        showToast("撤回成功,2s后自动关闭页面");
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                onFinishActivity();
                            }
                        }, 2000);
//                ConfirmDialog dialog=new  ConfirmDialog(TopicDetailsActivity.this,"提示","悬赏已经撤回,关闭本页面","取消",3);
//                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                    @Override
//                    public void confirm() {
//                        finish();
//                    }
//                });
//                dialog.show();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.i(TAG, "onFailure:" + t.getMessage());
                        showToast("系统错误");
                    }
                });
    }


    private String getGender(User targetUser) {
        String gender = null;
        if (targetUser.getGender() != null) {
            if (targetUser.getGender().equals("f")) {
                gender = "女";
            } else if (targetUser.getGender().equals("m")) {
                gender = "男";
            }
        } else {
            gender = "未设置";
        }
        return gender;
    }

    @Override
    public void onBackPressed() {
//        if (Jzvd.backPress()) {
//            return;
//        }
        if (hideCommentView()) {
            return;
        }

        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        JzvdStd.goOnPlayOnResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JzvdStd.goOnPlayOnPause();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (hideCommentView()) {
                return true;
            }
            onFinishActivity();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void onFinishActivity() {
        if (topicDelete) {
            setResult(Activity.RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic).putExtra(Constant.EXTRA_TOPIC_DELETE, topicDelete));
        } else {
            Intent intent = new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic);
            if (topicBackOut) {
                intent.putExtra(Constant.EXTRA_TOPIC_BACK_OUT, true);
            }
            if (topicChange) {
                intent.putExtra(Constant.EXTRA_TOPIC_CHANGE, true);
            }
            setResult(Activity.RESULT_OK, intent);
        }

        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JzvdStd.resetAllVideos();
        handler.removeCallbacks(runnable);

    }


    /**
     * 判断view 是否全部可见
     *
     * @param view
     * @return
     */
    private boolean isCover(View view) {
        boolean cover;
        Rect rect = new Rect();
        cover = view.getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= view.getMeasuredWidth() && rect.height() >= view.getMeasuredHeight()) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void onHideCommentView() {
        hideCommentView();
        // bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
    }

    @Override
    public void onLoadCommentSuccess(boolean hasNextCommentPage) {
        //isLoadingCommentData = false;
        // this.hasNextCommentPage = hasNextCommentPage;
        //  commentFooter.setVisibility(View.GONE);
    }

    @Override
    public void onLoadCommentError() {
        // isLoadingCommentData = false;
        //commentFooter.setVisibility(View.GONE);

    }

    @Override
    public void showToast(String message) {
        super.showToast(message);
    }

    public void firstLoadDataComplete(int topicPraiseSize, boolean hadPraise) {
        progressBar.setVisibility(View.GONE);
//        commentBottomBar.changeLikeImage(hadPraise);
//        commentBottomBar.setPraiseSize(topicPraiseSize);
    }

    @Override
    public void onCreateNormalCommentSuccess() {
        //如果是评论框隐藏状态发布的信息，在发布完成后，才隐藏掉评论的输入框
//        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {
//        }
        commentBottomBar.commitComplete();
        showToast_v1("评论成功！");
        //移动到评论区,延时500，不然可能没更新出来
        // sv_container.scrollTo(0,commentListView.getTop());

//        Handler handler = new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//
//                scrollToCommentView();
//            }
//        }, 500);
    }


    @Override
    public void onCreateChildCommentSuccess() {
        //如果是评论框隐藏状态发布的信息，在发布完成后，才隐藏掉评论的输入框
//        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {
//        }
        commentBottomBar.commitComplete();
        showToast_v1("评论成功！");
    }

    @Override
    public void onCreateCommentError() {
        commentBottomBar.setCommitButton(true);
        super.showToast(getString(R.string.system_busy));
    }

    @Override
    public void showProgressBar(boolean isShowProgressBar) {
        if (isShowProgressBar && !progressBar.isShown()) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (!isShowProgressBar && progressBar.isShown()) {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLoadDonationComplete() {
        if (refreshLayout != null) refreshLayout.refreshComplete();
    }

    @Override
    public void onHaveNotMoreData() {
        handler.postDelayed(runnable, 2000);
    }

    @Override
    public void onCommitDonationComplete(Double totalDonationAmount, Double donationBalance) {
        showToast(getString(R.string.donation_complete));
        topic.setDonationReceived(totalDonationAmount);
        if (topic.getType() != Constant.TOPIC_TYPE_EXPOSE) {
            topic.setDonationBalance(donationBalance);
        }
//        if (tv_donationAmount1 != null) {
//            tv_donationAmount1.setText(Utils.moneyFormat(totalDonationAmount));
//        }
        topic.setUpdated(new Date());
        topicChange = true;
    }

    @Override
    public void onCommentItemClick(String hint) {
        commentBottomBar.showHint(hint);
        commentBottomBar.showSoftKeyBord();
        if (bottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        }
        animateAndDisplayBottomBar(300);

    }

    @Override
    public void onCommit(String content) {
        hideSoftKeyboard();
        commentView.commitComment(content);
        //评论成功,当前topic改变
        topicChange = true;
    }

    @Override
    public void onAddPraise() {
        //点赞成功,当前topic改变
        topicChange = true;
//      Map<String, Object> info = new HashMap<>();
//        info.put("topicId", topic.getId());
//        info.put("uId", UserProfileManager.getInstance().getLoginUserInfo().getuId());
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .addTopicPraise(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();

                    }
                });
    }

    @Override
    public void onRemovePraise() {
        //撤销点赞成功，当前topic改变
        topicChange = true;
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .removeTopicPraise(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    @Override
    public void onPrepareComment() {
        commentView.prepareComment();

//        if (commentDialog == null) {
//
//            commentDialog = new CommentDialog(TopicDetailsActivity.this, topic, this);
//            commentDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                @Override
//                public void onDismiss(DialogInterface dialog) {
//                    commentBottomBar.hideCommentEditView();
//                }
//            });
//            commentDialog.show();
//        } else {
//            commentDialog.show();
//        }

        showCommentView();

    }

    @Override
    public void onApplyForManager() {
        applyForManager();
    }

    private void showCommentView() {
        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {

//            if (hasVideo) {//如果有视频
//                if (scrollY > screenHeight / 2) {//播放器向上滑出屏幕的一半，评论框全部展开
//                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
//                    bottomSheetBehavior.setSkipCollapsed(true);
//                } else {//半展开
//                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
//                    bottomSheetBehavior.setSkipCollapsed(false);
//                }
//            } else {//没有视频，全部展开
//                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
//                bottomSheetBehavior.setSkipCollapsed(true);
//
//            }
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            bottomSheetBehavior.setSkipCollapsed(false);
        }
    }

    @Override
    public void onLeftImageClick() {

        if (hideCommentView()) {
            return;
        }
        onFinishActivity();
    }

    @Override
    public void onRightImageClick() {
        showBottomDialog();
    }

    @Override
    public void onDialogItemViewClick(int position, String itemName) {
        if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_ACCUSATION)) {
            if (hadAccusation) {
                showToast_v1("已经举报过了哦！");
                return;
            }
            Accusation accusation = new Accusation();
            accusation.setTopicId(topicId);
            accusation.setAuthorId(author.getuId());
            accusation.setaUid(UserProfileManager.getInstance().getUserID());
            accusationTopic(accusation);
        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_EDIT)) {
            //如果是悬赏类型的主题，且悬赏任务正在执行中，不能编辑
            if (topic.getType() != null && topic.getType() == Constant.TOPIC_TYPE_REWARD && topic.getStatus() == Constant.TOPIC_STATUS_REWARD_EXECUTING) {
                showToast("悬赏任务正在执行中，不能编辑");
                return;
            }
            startActivityForResult(new Intent(TopicDetailsActivity.this, EditTopicActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), REQUEST_CODE_EDIT_TOPIC);

        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_MANAGE_DONATION)) {
            startActivityForResult(new Intent(TopicDetailsActivity.this, ForwardDonationActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), REQUEST_CODE_FORWARD_DONATION);
        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_REVOKE_REWARD)) {
            //如果是悬赏类型的主题，且悬赏任务正在执行中，不能编辑
            if (topic.getStatus() == Constant.TOPIC_STATUS_REWARD_EXECUTING) {
                showToast("悬赏任务正在执行中，不能拆回悬赏");
                return;
            }
            ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "确认撤回悬赏,退回保证金吗？", true);
            dialog.show();
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    revokeReward();
                }
            });
        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_DELETE)) {
            ConfirmDialog confirmDialog = new ConfirmDialog(this, "提醒", "确认删除吗？", true);
            confirmDialog.show();
            confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    deleteTopic(topic);
                }
            });
        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_EXIT_MANAGER)) {
            ConfirmDialog confirmDialogExit = new ConfirmDialog(TopicDetailsActivity.this, "提醒", "确认放弃管理权限吗?", true);
            confirmDialogExit.show();
            confirmDialogExit.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    exitManagerTopic(topic);
                }
            });
        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_SURRENDER_MANAGER)) {

            startActivityForResult(new Intent(TopicDetailsActivity.this, TransferAuthorityActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), TopicRecordActivity.REQUEST_CODE_DELETE_TOPIC);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_EDIT_TOPIC:
                topic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                init();
                topicChange = true;
                break;
            case REQUEST_CODE_FORWARD_DONATION:
                topic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                donationView.isDonationUpdate = true;
                loadTopicData(topicId, true);
                break;
            case REQUEST_CODE_TO_TASK_DETAIL_ACTIVITY:
                task = data.getParcelableExtra(Constant.EXTRA_INFO_TASK);
                break;
        }
    }

    @Override
    public void onCommentItemClick(Comment clickComment) {

    }


    /**
     * 获取赏金
     * <p>
     * 生成订单，表面双方的合作关系
     * 悬赏发起方，有权取消订单
     * 当发起方确认订单号，双方进入合作状态
     * ① 发起方有权发起取消合作，赏金猎人需要在6天时间内对订单做出处理，如果没做出处理，订单自动取消
     * 如果赏金猎人同意，订单取消，合作终止，
     * 如果 赏金猎人拒绝，定时任务停止  发起方可以再次取消订单，又进入订单取消 等待 赏金猎人确认状态，当猎人拒绝次数两次及以上，显示 联系客服 图标
     * <p>
     * ② 赏金猎人取消订单，订单直接取消
     * ③ 如果赏金猎人 点击 完成任务 ，需要发起方在6天做出处理，确认或者拒绝 ，如果没处理，默认完成任务，做结算处理。
     * 如果发起方 点拒绝，任务回滚为 未完成状态，删除定时任务，赏金猎人可以再次发起  完成任务，当发起方拒绝2次以上，显示 联系客服 图标，可以联系客服介入
     * 如果发起方点确认，做出结算处理，合作完成，删除定时任务；
     */
    private void generateTask() {

        RetrofitManager.getInstance().createRequest(TaskService.class)
                .generateTask(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast(btn_receiveTask, "悬赏任务已经结束");
                                    rewardComplete();
                                    break;
                                case Constant.REWARD_TASK_RECEIVED:
                                    isGetTheTask = true;
                                    taskReceived();
                                    break;
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 领取任务完成，已经通知悬赏发布者，等待对方确认，也可以主动联系对方");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        task = body.toJavaObject(Task.class);
                        isGetTheTask = true;
                        showToast(btn_receiveTask, "任务领取完成，等待对方确认");
                        taskReceived();
                        receiveTaskSize++;
                        tv_receiveTaskSize.setText(receiveTaskSize + "");
                        topic.setHadReceive(true);
                        topic.setReceiveTaskSize(receiveTaskSize);
                        topicChange = true;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());


                    }
                });


    }


    void deleteTopic(Topic topic) {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .delete_v1(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast("系统繁忙,请稍后重试");
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {

                                case Constant.TOPIC_TYPE_ERROR:
                                    showToast("主题类型错误，不能删除");
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast("主题状态错误，不能删除");
                                    break;
                                case Constant.DOC_ID_INVALID:
                                    showToast_v1("当前主题已被删除！");
                                    break;
                                default:
                                    showToast("系统繁忙,请稍后重试");
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 删除完成");
                        topicDelete = true;

                        showToast("删除成功,2s后自动跳转");
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                onFinishActivity();

                            }
                        }, 2000);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast("系统繁忙,请稍后重试");
                    }
                });
    }

    private void taskReceived() {
        //  btn_receiveTask.setEnabled(false);
        btn_receiveTask.setText("查看任务详情");
    }


    private void rewardComplete() {
        // btn_receiveTask.setEnabled(false);
        btn_receiveTask.setText("悬赏已完结");
    }

    private void rewardCancel() {
        // btn_receiveTask.setEnabled(false);
        btn_receiveTask.setText("悬赏已取消");
    }

    @Override
    public void onSendCouponComplete(Coupon coupon) {
        setResult(coupon);
    }

    @Override
    public void onReceiveCouponComplete(Coupon coupon) {
        setResult(coupon);
    }

    @Override
    public void onCouponStatusChange(Coupon coupon) {
        setResult(coupon);
    }

    private void setResult(Coupon coupon) {
        if (topic != null) {
            topic.setCoupon(coupon);
            topicChange = true;
        }
    }

    /**
     * 退出管理职务 放弃管理员权限
     *
     * @param topic
     */
    void exitManagerTopic(Topic topic) {
        progressBar.setVisibility(View.VISIBLE);
        //调用服务器端的接口完成退出管理操作
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .giveUpManager(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast("系统繁忙");
                            return;
                        }
                        if (result.isError()) {
                            Log.i(TAG, "onResponse:" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.NO_AUTHORITY:
                                    showToast("你不是管理员,权限不足");
                                    break;
                                case Constant.TOPIC_TYPE_ERROR:
                                    showToast("主题类型错误,不能退出管理");
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast("该主题目前已经管理员空缺状态，不能进行此操作，如有疑问，请联系客服");
                                    break;
                                default:
                                    showToast("系统繁忙,请稍后重试");
                            }
                            return;
                        }
                        showToast("放弃管理职务完成");
                        topic.setManager(null);
                        topic.setManagerId(null);
                        isManager = false;
                        commentBottomBar.onManagerGiveUp();
                        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(TopicDetailsActivity.this);
                        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_TOPIC_MANAGER_REMOVE).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);

                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast("系统出现错误");
                    }
                });

    }

    private void applyForManager() {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .applyForManager(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (body.isError()) {
                            switch (body.getStatus()) {
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast("该主题有管理员，不能申请成为管理员，如有疑问，请联系客服");
                                    break;
                            }

                            return;
                        }
                        showToast("申请成功，你已经成为管理员");
                        isManager = true;
                        commentBottomBar.onApplyManagerSuccess();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);

                    }
                });

    }

    @Override
    protected void onAccountChange() {
        super.onAccountChange();
        loadTopicData(topicId, true);
        commentBottomBar.showHintNotClearContent("说点什么");
        commentView.onAccountChange();
    }
}
